import requests
import base64
import os
import time
import random

class xigua_downloader(object):
    def __init__(self):
        self.video_path = './video'
        self.file_list = os.listdir(self.video_path)
        
    def set_user_agent(self):
        USER_AGENTS = [
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
            "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
            "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
            "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
            "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5"
        ]
        user_agent = random.choice(USER_AGENTS)
        return user_agent
    
    def spider(self, video_id):
        time.sleep(1)
        url = 'https://www.ixigua.com/api/public/videov2/brief/details?'
        params = {
            'group_id': video_id
        }
        headers = {
            'referer': f'https://www.ixigua.com/embed?group_id={video_id}',
            'cookie': 'MONITOR_WEB_ID=32ec01a7-8329-49fa-9dc7-e1b887baa413',
            'User-Agent':self.set_user_agent()
            }
        response = requests.get(url=url, headers=headers, params=params).json()
        
        try:
            download_url_b64 = response['data']['videoResource']['normal']['video_list']['video_4']['main_url']  #1080p是video_4
        except:
            try:
                download_url_b64 = response['data']['videoResource']['normal']['video_list']['video_3']['main_url']  #720p是video_3
            except:
                print('可能的错误为 1.视频仅有480p   2.限制流量（速度过快）  3.未知原因，建议打印response')
                #print(response)
                print(f'{video_id} 下载失败')
                with open('./log.txt', 'a+', encoding='utf-8') as fp:
                    fp.write(f'{video_id} 下载失败\n')
                    
            return
        #base64解码
        download_url = base64.b64decode(download_url_b64)
        title = response['data']['title']
        #print(download_url, title)
        return download_url, title
    
    
    def save_video(self, download_url, title):
        time.sleep(3)
        video_data = requests.get(download_url).content
        with open(f".\\{self.video_path}\{title}.mp4", 'wb') as fp:
            fp.write(video_data)
        
        
    def run(self, video_id):
        #创建文件夹
        if not os.path.exists(self.video_path):
            os.mkdir(self.video_path)
        
        #获取下载链接和标题
        try:
            download_url, title = self.spider(video_id)
        except:
            return
        
        #处理标题
        intab = "?*/\|.:><"
        outtab = "         "
        trantab = str.maketrans(intab, outtab)
        title = title.translate(trantab)
        
        #下载视频
        if title +'.mp4' in self.file_list:
            print(title +'.mp4 该文件已存在')
            return
        else:
            print(f'{title}.mp4 正在下载')
            self.save_video(download_url, title)
            print(f'{title}.mp4 下载完成')
    
        
if __name__ == "__main__":
    video_id = '6990943810020704781'
    downloader = xigua_downloader()
    downloader.run(video_id)
    